package com.gjy.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-01-24 11:28:31
 */
@Component
public class GlobalCacheRequestFilter implements Ordered, GlobalFilter {
    private static final Logger log = LoggerFactory.getLogger(GlobalCacheRequestFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("start GlobalCacheRequestFilter");
        // 只缓存json类型请求
        String header = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        boolean flag = StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
        // 不是json放行
        if (!flag) {
            return chain.filter(exchange);
        }
        // 使用 Gateway 自带工具 构建缓存body
        return ServerWebExchangeUtils.cacheRequestBody(exchange, (serverHttpRequest) -> {
            if (serverHttpRequest == exchange.getRequest()) {
                return chain.filter(exchange);
            }
            return chain.filter(exchange.mutate().request(serverHttpRequest).build());
        });
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
